package com.xyx.bloodoxygenlib.utils;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.xyx.bloodoxygenlib.services.ACSUtilityService;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;

/* loaded from: BDETrans.jar:com/bde/parentcyTransport/ACSUtility.class */
public class ACSUtility {
    private Context context;
    private Thread timerThread;
    private ArrayList<blePort> ports;
    private blePort currentPort;
    private int _lengthOfPackage;
    private float _scanTime;
    private Boolean bScanning;
    private byte[] receivedBuffer;
    private final String tag = "ACSUtility";
    private final int ACSUTILITY_SCAN_TIMEOUT_MSG = 1;
    private BluetoothAdapter mBtAdapter;
    private ACSUtilityService mService;
    private BluetoothManager bluetoothManager;
    private IACSUtilityCallback userCallback;
    private ServiceConnection conn;
    private Handler eventHandler;
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    Handler handler;

    /* loaded from: BDETrans.jar:com/bde/parentcyTransport/ACSUtility$IACSUtilityCallback.class */
    public interface IACSUtilityCallback {
        void utilReadyForUse();

        void didFoundPort(blePort bleport);

        void didFinishedEnumPorts();

        void didOpenPort(blePort bleport, Boolean bool);

        void didClosePort(blePort bleport);

        void didPackageSended(boolean z);

        void didPackageReceived(blePort bleport, byte[] bArr);

        void heartbeatDebug();
    }

    public ACSUtility() {
        this.ports = null;
        this.currentPort = null;
        this._lengthOfPackage = 10;
        this.bluetoothManager = null;
        this.conn = new ServiceConnection() { // from class: com.bde.parentcyTransport.ACSUtility.1
            @Override // android.content.ServiceConnection
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d("ACSUtility", "ACSUtilityService is connected!");
                ACSUtility.this.mService = ((ACSUtilityService.ACSBinder) service).getService();
                ACSUtility.this.mService.initialize();
                ACSUtility.this.mService.addEventHandler(ACSUtility.this.eventHandler);
                ACSUtility.this.userCallback.utilReadyForUse();
            }

            @Override // android.content.ServiceConnection
            public void onServiceDisconnected(ComponentName name) {
                Log.d("ACSUtility", "ACSUtilityService is disConnected!");
                ACSUtility.this.mService = null;
            }
        };
        this.eventHandler = new Handler() { // from class: com.bde.parentcyTransport.ACSUtility.2
            @Override // android.os.Handler
            public void handleMessage(Message msg) {
                if (ACSUtility.this.userCallback == null) {
                    Log.e("ACSUtility", "UserCallback is null! All event will not be handled!");
                    return;
                }
                switch (msg.what) {
                    case ACSUtilityService.EVENT_GATT_CONNECTED /* 1 */:
                    case ACSUtilityService.EVENT_DATA_RECEIVED /* 6 */:
                    default:
                        return;
                    case ACSUtilityService.EVENT_GATT_DISCONNECTED /* 2 */:
                        ACSUtility.this.mService.sendOver();
                        ACSUtility.this.userCallback.didClosePort(ACSUtility.this.currentPort);
                        return;
                    case ACSUtilityService.EVENT_GATT_SERVICES_DISCOVERED /* 3 */:
                        ACSUtility.this.userCallback.didOpenPort(ACSUtility.this.currentPort, false);
                        return;
                    case ACSUtilityService.EVENT_OPEN_PORT_SUCCEED /* 4 */:
                        ACSUtility.this.userCallback.didOpenPort(ACSUtility.this.currentPort, true);
                        return;
                    case ACSUtilityService.EVENT_DATA_AVAILABLE /* 5 */:
                        ACSUtility.this.userCallback.didPackageReceived(ACSUtility.this.currentPort, msg.getData().getByteArray(ACSUtilityService.EXTRA_DATA));
                        return;
                    case ACSUtilityService.EVENT_HEART_BEAT_DEBUG /* 7 */:
                        ACSUtility.this.userCallback.heartbeatDebug();
                        return;
                    case ACSUtilityService.EVENT_DATA_SEND_SUCEED /* 8 */:
                        ACSUtility.this.userCallback.didPackageSended(true);
                        ACSUtility.this.mService.sendOver();
                        return;
                    case ACSUtilityService.EVENT_DATA_SEND_FAILED /* 9 */:
                        ACSUtility.this.userCallback.didPackageSended(false);
                        ACSUtility.this.mService.sendOver();
                        return;
                }
            }
        };
        this.mLeScanCallback = new BluetoothAdapter.LeScanCallback() { // from class: com.bde.parentcyTransport.ACSUtility.3
            @Override // android.bluetooth.BluetoothAdapter.LeScanCallback
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                Log.d("ACSUtility", "onScanResult() - deviceName = " + device.getName() + ", rssi=" + rssi + ",lengthOfScanRecord is : " + scanRecord.length + ",address : " + device.getAddress());
                if (!ACSUtility.this.checkAddressExist(device).booleanValue()) {
                    if (ACSUtility.this.ports == null) {
                        ACSUtility.this.ports = new ArrayList();
                    }
                    Log.d("ACSUtility", "==== new Port add here ====");
                    blePort newPort = new blePort(device);
                    ACSUtility.this.ports.add(newPort);
//                    device.getName().equals("BDE_SPP");
                    if (ACSUtility.this.userCallback != null) {
                        ACSUtility.this.userCallback.didFoundPort(newPort);
                    }
                }
            }
        };
        this.handler = new Handler() { // from class: com.bde.parentcyTransport.ACSUtility.4
            @Override // android.os.Handler
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ACSUtilityService.EVENT_GATT_CONNECTED /* 1 */:
                        Log.d("ACSUtility", "scan time out");
                        ACSUtility.this.bScanning = false;
                        ACSUtility.this.mBtAdapter.stopLeScan(ACSUtility.this.mLeScanCallback);
                        if (ACSUtility.this.userCallback != null) {
                            ACSUtility.this.userCallback.didFinishedEnumPorts();
                            break;
                        }
                        break;
                }
                ACSUtility.this.timerThread = null;
                super.handleMessage(msg);
            }
        };
        Log.d("ACSUtility", "ACS Utility Constructor");
    }

    public ACSUtility(Context context, IACSUtilityCallback cb) {
        this.ports = null;
        this.currentPort = null;
        this._lengthOfPackage = 10;
        this.bluetoothManager = null;
        this.conn = new ServiceConnection() { // from class: com.bde.parentcyTransport.ACSUtility.1
            @Override // android.content.ServiceConnection
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d("ACSUtility", "ACSUtilityService is connected!");
                ACSUtility.this.mService = ((ACSUtilityService.ACSBinder) service).getService();
                ACSUtility.this.mService.initialize();
                ACSUtility.this.mService.addEventHandler(ACSUtility.this.eventHandler);
                ACSUtility.this.userCallback.utilReadyForUse();
            }

            @Override // android.content.ServiceConnection
            public void onServiceDisconnected(ComponentName name) {
                Log.d("ACSUtility", "ACSUtilityService is disConnected!");
                ACSUtility.this.mService = null;
            }
        };
        this.eventHandler = new Handler() { // from class: com.bde.parentcyTransport.ACSUtility.2
            @Override // android.os.Handler
            public void handleMessage(Message msg) {
                if (ACSUtility.this.userCallback == null) {
                    Log.e("ACSUtility", "UserCallback is null! All event will not be handled!");
                    return;
                }
                switch (msg.what) {
                    case ACSUtilityService.EVENT_GATT_CONNECTED /* 1 */:
                    case ACSUtilityService.EVENT_DATA_RECEIVED /* 6 */:
                    default:
                        return;
                    case ACSUtilityService.EVENT_GATT_DISCONNECTED /* 2 */:
                        ACSUtility.this.mService.sendOver();
                        ACSUtility.this.userCallback.didClosePort(ACSUtility.this.currentPort);
                        return;
                    case ACSUtilityService.EVENT_GATT_SERVICES_DISCOVERED /* 3 */:
                        ACSUtility.this.userCallback.didOpenPort(ACSUtility.this.currentPort, false);
                        return;
                    case ACSUtilityService.EVENT_OPEN_PORT_SUCCEED /* 4 */:
                        ACSUtility.this.userCallback.didOpenPort(ACSUtility.this.currentPort, true);
                        return;
                    case ACSUtilityService.EVENT_DATA_AVAILABLE /* 5 */:
                        ACSUtility.this.userCallback.didPackageReceived(ACSUtility.this.currentPort, msg.getData().getByteArray(ACSUtilityService.EXTRA_DATA));
                        return;
                    case ACSUtilityService.EVENT_HEART_BEAT_DEBUG /* 7 */:
                        ACSUtility.this.userCallback.heartbeatDebug();
                        return;
                    case ACSUtilityService.EVENT_DATA_SEND_SUCEED /* 8 */:
                        ACSUtility.this.userCallback.didPackageSended(true);
                        ACSUtility.this.mService.sendOver();
                        return;
                    case ACSUtilityService.EVENT_DATA_SEND_FAILED /* 9 */:
                        ACSUtility.this.userCallback.didPackageSended(false);
                        ACSUtility.this.mService.sendOver();
                        return;
                }
            }
        };
        this.mLeScanCallback = new BluetoothAdapter.LeScanCallback() { // from class: com.bde.parentcyTransport.ACSUtility.3
            @Override // android.bluetooth.BluetoothAdapter.LeScanCallback
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                String name = device.getName();
//                if(name == null){
//                    name = BleUtil.parseAdertisedData(scanRecord).getName();
//                }
                Log.d("ACSUtility", "onScanResult() - deviceName = " + name + ", rssi=" + rssi + ",lengthOfScanRecord is : " + scanRecord.length + ",address : " + device.getAddress());
                if (!ACSUtility.this.checkAddressExist(device).booleanValue()) {
                    if (ACSUtility.this.ports == null) {
                        ACSUtility.this.ports = new ArrayList();
                    }
                    Log.d("ACSUtility", "==== new Port add here ====");
                    blePort newPort = new blePort(device);
                    ACSUtility.this.ports.add(newPort);
//                    name.equals("BDE_SPP");
                    if (ACSUtility.this.userCallback != null) {
                        ACSUtility.this.userCallback.didFoundPort(newPort);
                    }
                }
            }
        };
        this.handler = new Handler() { // from class: com.bde.parentcyTransport.ACSUtility.4
            @Override // android.os.Handler
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ACSUtilityService.EVENT_GATT_CONNECTED /* 1 */:
                        Log.d("ACSUtility", "scan time out");
                        ACSUtility.this.bScanning = false;
                        ACSUtility.this.mBtAdapter.stopLeScan(ACSUtility.this.mLeScanCallback);
                        if (ACSUtility.this.userCallback != null) {
                            ACSUtility.this.userCallback.didFinishedEnumPorts();
                            break;
                        }
                        break;
                }
                ACSUtility.this.timerThread = null;
                super.handleMessage(msg);
            }
        };
        this.context = context;
        this.userCallback = cb;
        this._lengthOfPackage = 10;
        this.bScanning = false;
        Log.d("ACSUtility", "acsUtility 1");
        this.bluetoothManager = (BluetoothManager) context.getSystemService("bluetooth");
        this.mBtAdapter = this.bluetoothManager.getAdapter();
        if (this.mBtAdapter == null) {
            Log.d("ACSUtility", "error,mBtAdapter == null");
            return;
        }
        Intent intent = new Intent();
        intent.setClass(context, ACSUtilityService.class);
        context.startService(intent);
        context.bindService(intent, this.conn, 1);
    }

    public void enumAllPorts(float time) {
        this.ports = null;
        this._scanTime = time;
        if (this.bScanning.booleanValue()) {
            Log.e("ACSUtility", "enum in progress,could not execute again");
            return;
        }
        Log.d("ACSUtility", "start scan now");
        this.mBtAdapter.stopLeScan(this.mLeScanCallback);
        this.mBtAdapter.startLeScan(this.mLeScanCallback);
        this.bScanning = true;
        this.timerThread = new Thread(new myThread(this, null));
        this.timerThread.setName("timerThread");
        this.timerThread.start();
    }

    public boolean isPortOpened(blePort port) {
        if (this.mService != null && this.mService.mBluetoothGatt != null && this.bluetoothManager.getConnectionState(port._device, 7) == 2) {
            return true;
        }
        Log.e("ACSUtility", "mService or mService.mBluetoothGatt is null.We can't know whether the port is opened.");
        return false;
    }

    public void stopEnum() {
        this.bScanning = false;
        this.mBtAdapter.stopLeScan(this.mLeScanCallback);
    }

    public void openPort(blePort port) {
        if (this.mService == null || port == null) {
            Log.e("ACSUtility", "ACSUtilityService or port is null!");
            return;
        }
        this.currentPort = port;
        this.mService.connect(port._device.getAddress());
    }

    public void openPort(String address) {
        if (this.mService == null || address == null || !BluetoothAdapter.checkBluetoothAddress(address)) {
            Log.e("ACSUtility", "ACSUtilityService or port is null!");
        } else {
            this.mService.connect(address);
        }
    }

    public void closePort() {
        this.mService.disconnect();
    }

    public void configurePort(blePort port, int lenghOfPackage) {
        this._lengthOfPackage = lenghOfPackage;
    }

    public boolean writePort(byte[] value) {
        if (value != null) {
            return this.mService.writePort(value);
        }
        Log.e("ACSUtility", "Write port failed...value is null...");
        return false;
    }

    public void closeACSUtility() {
        this.mService.close();
        this.mService.removeEventHandler();
        this.context.unbindService(this.conn);
        Intent intent = new Intent();
        intent.setClass(this.context, ACSUtilityService.class);
        this.context.stopService(intent);
    }

    protected void openPortFailAction() {
        if (this.userCallback != null) {
            this.userCallback.didOpenPort(this.currentPort, false);
        }
    }

    protected void openPortSuccessAction() {
        if (this.userCallback != null) {
            this.userCallback.didOpenPort(this.currentPort, true);
        }
    }

    protected String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte b : src) {
            String hv = Integer.toHexString(b & 255);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        stringBuilder.append('\n');
        return stringBuilder.toString();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public Boolean checkAddressExist(BluetoothDevice device) {
        if (this.ports == null) {
            return false;
        }
        Iterator<blePort> it = this.ports.iterator();
        while (it.hasNext()) {
            if (it.next()._device.getAddress().equals(device.getAddress())) {
                return true;
            }
        }
        return false;
    }

    protected void checkPackageToSend(byte[] newData) {
        if (this.receivedBuffer != null) {
            Log.d("ACSUtility", "checkPachageToSend buffer length is " + this.receivedBuffer.length);
            byte[] tempBuffer = new byte[this.receivedBuffer.length + newData.length];
            byteCopy(this.receivedBuffer, tempBuffer, 0, 0, this.receivedBuffer.length);
            byteCopy(newData, tempBuffer, 0, this.receivedBuffer.length, newData.length);
            this.receivedBuffer = null;
            this.receivedBuffer = tempBuffer;
        } else {
            Log.d("ACSUtility", "checkPachageToSend buffer is null !");
            this.receivedBuffer = new byte[newData.length];
            byteCopy(newData, this.receivedBuffer, 0, 0, newData.length);
        }
        Log.d("ACSUtility", "buffer lenght now is " + this.receivedBuffer.length);
        if (this.receivedBuffer.length >= this._lengthOfPackage) {
            byte[] packageToSend = new byte[this._lengthOfPackage];
            byte[] tempBuffer2 = new byte[this.receivedBuffer.length - this._lengthOfPackage];
            byteCopy(this.receivedBuffer, packageToSend, 0, 0, this._lengthOfPackage);
            byteCopy(this.receivedBuffer, tempBuffer2, this._lengthOfPackage, 0, tempBuffer2.length);
            this.receivedBuffer = null;
            this.receivedBuffer = tempBuffer2;
            this.userCallback.didPackageReceived(this.currentPort, packageToSend);
            Log.d("ACSUtility", "left length is " + this.receivedBuffer.length);
        }
    }

    private void byteCopy(byte[] from, byte[] to, int fromIndex, int toIndex, int length) {
        int realLength = from.length < length ? from.length : length;
        for (int i = 0; i < realLength; i++) {
            to[i + toIndex] = from[i + fromIndex];
        }
    }

    /* loaded from: BDETrans.jar:com/bde/parentcyTransport/ACSUtility$myThread.class */
    private class myThread implements Runnable {
        private myThread() {
        }

        /* synthetic */ myThread(ACSUtility aCSUtility, myThread mythread) {
            this();
        }

        @Override // java.lang.Runnable
        public void run() {
            try {
                Thread.sleep(((long) ACSUtility.this._scanTime) * 1000);
                if (ACSUtility.this.bScanning.booleanValue()) {
                    ACSUtility.this.handler.sendEmptyMessage(1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /* loaded from: BDETrans.jar:com/bde/parentcyTransport/ACSUtility$blePort.class */
    public class blePort implements Serializable {
        private static final long serialVersionUID = 1;
        public BluetoothDevice _device;

        public blePort(BluetoothDevice device) {
            this._device = device;
        }
    }

    public void printHexString(byte[] b) {
        for (byte b2 : b) {
            String hex = Integer.toHexString(b2 & 255);
            if (hex.length() == 1) {
                hex = String.valueOf('0') + hex;
            }
            Log.d("ACSUtility", hex);
        }
    }
}